package com.example.controller;

import com.example.common.Result;
import com.example.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    
    @Autowired
    private OssService ossService;
    
    /**
     * 上传文件
     * @param file 文件
     * @return 文件访问URL
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 按日期创建文件夹
            String folder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            
            // 上传文件
            String fileUrl = ossService.uploadFile(file, folder);
            
            if (fileUrl != null) {
                return Result.success(fileUrl);
            } else {
                return Result.error("文件上传失败");
            }
        } catch (Exception e) {
            log.error("文件上传异常", e);
            return Result.error("文件上传异常: " + e.getMessage());
        }
    }
}